import { View, Image, Input, Text } from "@tarojs/components";

import { useEffect, useState } from "react";
import {
  AtAccordion,
  AtButton,
  AtDivider,
  AtIcon,
  AtList,
  AtListItem,
} from "taro-ui3";
import styles from "./index.module.scss";

interface SendCodeProps {
    send: (data: { phone: string; code: string }) => void;
    mobile: { phone: string; code: string }
}

const SendCode = (props: SendCodeProps) => {
  const [phone, setPhone] = useState<string>("");
  const [open, setOpen] = useState<boolean>(false);
  const [isError, setError] = useState<boolean>(false);
  const onChange = (e) => {
    setPhone(e.target.value);
  };
  const sendCode = () => {
    if (!phone || phone.length !== 11) {
      setError(true);
      return;
    }
    props.send({phone, code: '+86' });
  };
  const accordionClick = () => {
    setOpen(!open);
  };

  const clear = () => {
    setPhone('');
  };

  const onBlur = () => {
    if (!phone || phone.length !== 11) {
      setError(true);
    } else {
      setError(false);
    }
  };

  useEffect(() => {
    setPhone(props.mobile.phone);
  }, [])

  return (
    <View className={styles["send-code-container"]}>
      <View>
        <View className={styles["login-input"]}>
          <View className={styles["flag-container"]}>
            <Image
              className={styles["flag"]}
              src={require("@/assets/images/china.webp")}
              mode={"aspectFill"}
            />
          </View>
          <AtAccordion
            title="+86"
            open={open}
            onClick={accordionClick}
            style={{ color: "#ccc" }}
            customStyle={{ width: "80px" }}
          >
            <AtList hasBorder={false}>
              <AtListItem title="+01" thumb="" />
            </AtList>
          </AtAccordion>
          <Input
            type="text"
            placeholder="请输入手机号码"
            focus
            onFocus={() => {
              setError(false);
            }}
            value={phone}
            onInput={onChange}
            maxlength={11}
            onBlur={onBlur}
          />
          <View className={styles["input-close"]} onClick={clear}>
            <AtIcon value="close" size="8" color="#fff"></AtIcon>
          </View>
        </View>
        <AtDivider className={styles["input-divider"]} />
        {isError ? (
          <Text className={styles["error-text"]}>请输入正确的手机号</Text>
        ) : null}
      </View>
      <AtButton className={styles["login-btn"]} onClick={sendCode}>
        发送验证码
      </AtButton>
    </View>
  );
};

export default SendCode;
